package cn.smilefox.controller;


import cn.smilefox.domain.Use;
import cn.smilefox.service.UseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/uses")
@Controller
public class UseController {

    @Autowired
    private UseService useService;

    //登录
    @RequestMapping("/login")
    public ModelAndView login(Use use){
        ModelAndView modelAndView = new ModelAndView();
        Use use1 = useService.login(use);

        String name = use.getUse_name();
        if (use1.getUse_password().equals(use.getUse_password())){
            System.out.println(use1);
            modelAndView.addObject("use1",use1);
            modelAndView.setViewName("main");
            return modelAndView;
        }
        else {
            Use use2 = new Use();
            modelAndView.addObject("use1",use1);
            modelAndView.setViewName("login");
            System.out.println();
            return modelAndView;
        }
    };

    //注册
    @RequestMapping("/register")
    public String register(Use use){

        useService.register(use);

        return "redirect:/login.jsp";
    };

    //验证用户名一致性
    @RequestMapping("/namecheck/{use_name}")
//    //重定向版
//    public String namecheck(@PathVariable("use_name") String use_name, HttpServletRequest request){
//        boolean check = useService.namecheck(use_name);
//        System.out.println("----------测试---------------");
//        System.out.println(use_name);
//        System.out.println(check);
//        request.setAttribute("check",check);
//        Use use = new Use();
//        use.setUse_name(use_name);
//        if (check){
//            return "redirect:/register.jsp?name="+use_name+"";
//        }else {
//            String name = "";
//            return "redirect:/register.jsp?check="+true+"";
//        }
//
//    };
    //不重定向版
    @ResponseBody
    public String namecheck(@PathVariable("use_name") String use_name, HttpServletRequest request){
        boolean check = useService.namecheck(use_name);
        if (check){
            request.setAttribute("use_name",use_name);
            return "";
        }else {
            request.setAttribute("check",true);
            return "";
        }

    };


}
